<template>
  <div class="user-manage">
    <div class="page-header">
      <h1>用户管理</h1>
      <p>管理系统中的所有用户信息</p>
    </div>

    <!-- 搜索和操作区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="邮箱">
          <el-input
            v-model="searchForm.email"
            placeholder="请输入邮箱"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="角色">
          <el-select
            v-model="searchForm.role"
            placeholder="请选择角色"
            clearable
            style="width: 120px"
          >
            <el-option label="管理员" :value="0" />
            <el-option label="普通用户" :value="1" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="operation-buttons">
        <el-button
          type="primary"
          @click="handleAdd"
        >
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
        
        <el-button
          type="danger"
          :disabled="selectedUsers.length === 0"
          @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="id" label="ID" width="80" />
        
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :size="40" :src="getAvatarUrl(row.avatar)">
              <el-icon><UserFilled /></el-icon>
            </el-avatar>
          </template>
        </el-table-column>
        
        <el-table-column prop="username" label="用户名" width="120" />
        
        <el-table-column prop="email" label="邮箱" width="200" show-overflow-tooltip />
        
        <el-table-column prop="phone" label="手机号" width="140" />
        
        <el-table-column label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.role === 0 ? 'danger' : 'primary'">
              {{ row.role === 0 ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="性别" width="80">
          <template #default="{ row }">
            {{ getGenderText(row.gender) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            
            <el-button
              type="warning"
              size="small"
              @click="handleResetPassword(row)"
            >
              重置密码
            </el-button>
            
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="showUserDialog"
      :title="dialogTitle"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="80px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="userForm.username"
                placeholder="请输入用户名"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12" v-if="!isEdit">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="userForm.password"
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="userForm.email"
                placeholder="请输入邮箱"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="userForm.phone"
                placeholder="请输入手机号"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="角色" prop="role">
              <el-select v-model="userForm.role" placeholder="请选择角色">
                <el-option label="普通用户" :value="1" />
                <el-option label="管理员" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="userForm.status" placeholder="请选择状态">
                <el-option label="正常" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="userForm.gender" placeholder="请选择性别">
                <el-option label="未知" :value="0" />
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="userForm.birthday"
            type="date"
            placeholder="请选择生日"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="userForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showUserDialog = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitLoading"
          @click="handleSubmit"
        >
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Delete,
  UserFilled
} from '@element-plus/icons-vue'
import userManageApi from '@/api/userManage'

// 响应式数据
const loading = ref(false)
const userList = ref([])
const selectedUsers = ref([])
const showUserDialog = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const currentUserId = ref(null)

// 搜索表单
const searchForm = reactive({
  username: '',
  email: '',
  role: null,
  status: null
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 用户表单
const userForm = reactive({
  username: '',
  password: '',
  email: '',
  phone: '',
  role: 1,
  status: 1,
  gender: 0,
  birthday: '',
  remark: ''
})

// 表单引用
const userFormRef = ref()

// 对话框标题
const dialogTitle = computed(() => isEdit.value ? '编辑用户' : '新增用户')

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取头像URL
const getAvatarUrl = (avatar) => {
  if (!avatar) return ''
  if (avatar.startsWith('http')) return avatar
  return `/api${avatar}`
}

// 获取性别文本
const getGenderText = (gender) => {
  const genderMap = {
    0: '未知',
    1: '男',
    2: '女'
  }
  return genderMap[gender] || '未知'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 加载用户列表
const loadUserList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    
    const response = await userManageApi.pageUsers(params)
    
    if (response.code === 200) {
      userList.value = response.data.records
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取用户列表失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadUserList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    email: '',
    role: null,
    status: null
  })
  pagination.current = 1
  loadUserList()
}

// 新增用户
const handleAdd = () => {
  isEdit.value = false
  currentUserId.value = null
  resetUserForm()
  showUserDialog.value = true
}

// 编辑用户
const handleEdit = async (row) => {
  isEdit.value = true
  currentUserId.value = row.id
  
  try {
    const response = await userManageApi.getUserById(row.id)
    if (response.code === 200) {
      Object.assign(userForm, response.data)
      showUserDialog.value = true
    } else {
      ElMessage.error(response.message || '获取用户信息失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '获取用户信息失败')
  }
}

// 删除用户
const handleDelete = async (row) => {
  await ElMessageBox.confirm(
    `确定要删除用户 "${row.username}" 吗？此操作不可恢复！`,
    '警告',
    {
      type: 'warning'
    }
  )
  
  try {
    const response = await userManageApi.deleteUser(row.id)
    if (response.code === 200) {
      ElMessage.success('用户删除成功')
      await loadUserList()
    } else {
      ElMessage.error(response.message || '删除用户失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '删除用户失败')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  const usernames = selectedUsers.value.map(user => user.username).join('、')
  
  await ElMessageBox.confirm(
    `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？\n用户：${usernames}\n此操作不可恢复！`,
    '警告',
    {
      type: 'warning'
    }
  )
  
  try {
    const ids = selectedUsers.value.map(user => user.id)
    const response = await userManageApi.batchDeleteUsers(ids)
    
    if (response.code === 200) {
      ElMessage.success('批量删除成功')
      selectedUsers.value = []
      await loadUserList()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '批量删除失败')
  }
}

// 重置密码
const handleResetPassword = async (row) => {
  await ElMessageBox.confirm(
    `确定要重置用户 "${row.username}" 的密码吗？`,
    '确认重置',
    {
      type: 'warning'
    }
  )
  
  try {
    const response = await userManageApi.resetPassword(row.id)
    if (response.code === 200) {
      ElMessageBox.alert(
        `用户 "${row.username}" 的新密码是：${response.data}\n请告知用户及时修改密码！`,
        '密码重置成功',
        {
          type: 'success'
        }
      )
    } else {
      ElMessage.error(response.message || '重置密码失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '重置密码失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return

  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        let response
        
        if (isEdit.value) {
          // 编辑用户时不传密码
          const { password, username, ...updateData } = userForm
          response = await userManageApi.updateUser(currentUserId.value, updateData)
        } else {
          // 新增用户
          response = await userManageApi.createUser(userForm)
        }
        
        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '用户更新成功' : '用户创建成功')
          showUserDialog.value = false
          await loadUserList()
        } else {
          ElMessage.error(response.message || (isEdit.value ? '用户更新失败' : '用户创建失败'))
        }
      } catch (error) {
        ElMessage.error(error.message || (isEdit.value ? '用户更新失败' : '用户创建失败'))
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置用户表单
const resetUserForm = () => {
  Object.assign(userForm, {
    username: '',
    password: '',
    email: '',
    phone: '',
    role: 1,
    status: 1,
    gender: 0,
    birthday: '',
    remark: ''
  })
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadUserList()
}

// 页码变化
const handleCurrentChange = (current) => {
  pagination.current = current
  loadUserList()
}

onMounted(() => {
  loadUserList()
})
</script>

<style lang="scss" scoped>
.user-manage {
  .page-header {
    margin-bottom: 24px;
    
    h1 {
      font-size: 24px;
      color: #303133;
      margin: 0 0 8px 0;
    }
    
    p {
      color: #606266;
      margin: 0;
    }
  }
  
  .search-card {
    margin-bottom: 24px;
    
    .operation-buttons {
      margin-top: 16px;
      text-align: right;
    }
  }
  
  .table-card {
    .pagination-wrapper {
      margin-top: 20px;
      text-align: right;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .user-manage {
    .search-card {
      :deep(.el-form--inline) {
        .el-form-item {
          display: block;
          margin-bottom: 16px;
          
          .el-form-item__content {
            margin-left: 0 !important;
          }
        }
      }
      
      .operation-buttons {
        text-align: left;
      }
    }
    
    .table-card {
      overflow-x: auto;
      
      .pagination-wrapper {
        text-align: center;
      }
    }
  }
}
</style> 